package com.cgc.venus.server.job.jobdetail;
import com.cgc.venus.server.core.k8s.impl.K8sStorageServiceImpl;
import com.cgc.venus.server.core.k8s.inter.K8sStorageService;
import com.cgc.venus.server.core.utils.SpringUtil;
import com.cgc.venus.server.core.utils.StringUtil;
import com.cgc.venus.server.job.Constants;
import com.cgc.venus.server.job.bean.PersistentVolumeClaimBean;
import com.cgc.venus.server.job.config.JobConfig;
import io.fabric8.kubernetes.api.model.PersistentVolumeClaim;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 统计存储
 */
public class StatsStorageJob extends AbstractBaseJob {
    private static Logger logger = LoggerFactory.getLogger(StatsStorageJob.class);
    public StatsStorageJob() {
    }
    public void execute(JobExecutionContext context)  
        throws JobExecutionException {
        logger.info("统计存储job start...");
        List objs = new ArrayList<Object>();
        String sql="";
        String id="";
        try {
            //查询统计信息
            K8sStorageService k8sStorageService=SpringUtil.getBean(K8sStorageServiceImpl.class);
            List<PersistentVolumeClaim> results= k8sStorageService.getPersistentVolumeClaims("");
            JobConfig jobConfig=SpringUtil.getBean(JobConfig.class);
            Double storage_count_all=jobConfig.getStorage_count_all();
            Double storage_count_req=0.0;
            Double storage_count_req_using=0.0;
            Double storage_count_req_unuse=0.0;
            Double storage_count_req_today=0.0;
            if(results!=null&&results.size()>0){
                List<PersistentVolumeClaimBean> pvcbs=convertToPersistentVolumeClaimBean(results);
                Map<Integer,Double> m = pvcbs.stream().collect(
                        Collectors.groupingBy(PersistentVolumeClaimBean::getUsType, Collectors.summingDouble(PersistentVolumeClaimBean::getReqSize)));
                Map<String,Double> m1 = pvcbs.stream().collect(
                        Collectors.groupingBy(PersistentVolumeClaimBean::getIsToday, Collectors.summingDouble(PersistentVolumeClaimBean::getReqSize)));
                Double d0=m.get(new Integer(0))==null?0.0:m.get(new Integer(0));
                Double d1=m.get(new Integer(1))==null?0.0:m.get(new Integer(1));
                Double d2=m1.get("true")==null?0.0:m1.get("true");
                storage_count_req=d0+d1;
                storage_count_req_using=d0;
                storage_count_req_unuse=d1;
                storage_count_req_today=d2;
            }
            //处理告警
            if(storage_count_req>storage_count_all){
                //往告警表插入一条记录
                String alertMsg="存储请求总量"+storage_count_req+",大于存储总量!"+storage_count_all+"";
                handleEx(alertMsg,Constants.ALARM_TYPE_STORAGE,Constants.ALARM_STATUS_UN,Constants.ALARM_LEVEL_HIGHEST,Constants.ALARM_NS_ALL);
            }
            //更新统计值表
            sql="select id from t_job_stats_storage where date_format(create_time,'%Y-%m-%d')=date_format(NOW(),'%Y-%m-%d')";
            List<Map<String, Object>> l=getJdbcTemplate().queryForList(sql);
            if(l!=null&&l.size()>0){
                //db update
                sql = "update t_job_stats_storage  set storage_count_all=?,storage_count_req=?,storage_count_req_using=?,storage_count_req_unuse=?,storage_count_req_today=?,last_update_time=NOW() where id=?";
                id=l.get(0).get("id").toString();
            }else{
                //db insert
                sql = "INSERT INTO t_job_stats_storage(storage_count_all,storage_count_req,storage_count_req_using,storage_count_req_unuse,storage_count_req_today,id,create_time,last_update_time) VALUES (?,?,?,?,?,?,NOW(),NOW())";
                id = StringUtil.getUUID();
            }
            objs.add(storage_count_all);
            objs.add(storage_count_req);
            objs.add(storage_count_req_using);
            objs.add(storage_count_req_unuse);
            objs.add(storage_count_req_today);
            objs.add(id);
            getJdbcTemplate().update(sql, objs.toArray());
        }catch (Exception ex){
            logger.error(ex.getMessage(),ex);
            handleEx("统计存储任务异常,异常信息:"+getErrorInfoFromException(ex),Constants.ALARM_TYPE_JOB_ERROR,Constants.ALARM_STATUS_UN,Constants.ALARM_LEVEL_HIGHEST,Constants.ALARM_NS_ALL);
            throw new JobExecutionException(ex);
        }
    }

    private List<PersistentVolumeClaimBean> convertToPersistentVolumeClaimBean(List<PersistentVolumeClaim> pvcs){
        List<PersistentVolumeClaimBean> pvcbs=new ArrayList<PersistentVolumeClaimBean>();
        PersistentVolumeClaimBean pvcb=null;
        Double reqSize=0.0;//请求大小
        int usType=1;//使用类型 (0 已经使用 1未使用)
        String isToday="false";//是否今天存储
        Map<String,String> m=null;
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
        for(PersistentVolumeClaim pvc:pvcs){
            String storageSize=pvc.getSpec().getResources().getRequests().get("storage").getAmount();
            BigDecimal bd=new BigDecimal(storageSize.substring(0, storageSize.length() - 2));
            if(storageSize.toUpperCase().indexOf("M")!=-1){
                bd=bd.divide(new BigDecimal(1024), 2);//转成G
            }
            if(storageSize.toUpperCase().indexOf("K")!=-1){
                bd=bd.divide(new BigDecimal(1024*1024), 2);//转成G
            }
            reqSize=bd.doubleValue();
            m=pvc.getMetadata().getAnnotations();
            if(m==null){
                usType=1;
            }else{
                if(m.get(K8sStorageServiceImpl.ANNOTATION_KYE_APP)==null){
                    usType=1;
                }else{
                    usType=0;
                }
            }
            String time=pvc.getMetadata().getCreationTimestamp().split("T")[0];
            if(time.equals(sdf.format(new Date()))){
                isToday="true";
            }else{
                isToday="false";
            }
            pvcb=new PersistentVolumeClaimBean(reqSize,usType,isToday);
            pvcbs.add(pvcb);
        }
        return pvcbs;
    }
}